﻿using UnityEngine;
using System.Collections;

public class CameraAuto : MonoBehaviour {

	// 默认屏幕大小  
    public float width = 960f;  
	public float height = 640f;  

	public float smoothSpeed = 0.001f;

	public float yMaxMove = 1f;

	public float xMaxMove = 1f;

	private Transform player;

	private Vector3 cameraVelocity = Vector3.zero;

	private Vector3 target;

	private Vector3 centerPosition;

    // Use this for initialization  
    void Awake()  
    {  
        // 屏幕适配  
        float orthographicSize = this.GetComponent<Camera>().orthographicSize;
        orthographicSize *= (Screen.height / (float)Screen.width) / (height / width);
        this.GetComponent<Camera>().orthographicSize = orthographicSize;
    }

    public void SetCenterPosition(Vector3 position) {
        centerPosition = new Vector3(position.x,position.y,transform.position.z);
        target = centerPosition;
    }

    bool fixSmooth;
	void FixedUpdate(){
		if(!GameSetting.GAME_START){
			return;
		}
		if( player == null ){
			GameObject obj = GameObject.FindWithTag("Player");
			if(obj){
				player = obj.transform;
			}
		}
		if(player){
			target.y = Mathf.SmoothDamp(transform.position.y, player.position.y, ref cameraVelocity.y, smoothSpeed);
			target.x = Mathf.SmoothDamp(transform.position.x, player.position.x, ref cameraVelocity.x, smoothSpeed);

			if( target.x >= centerPosition.x + xMaxMove ){
				target.x = centerPosition.x + xMaxMove;
			}else if (target.x < centerPosition.x - xMaxMove){
				target.x = centerPosition.x - xMaxMove;
			}

			if( target.y >= centerPosition.y + yMaxMove ){
				target.y = centerPosition.y + yMaxMove;
			}else if (target.y < centerPosition.y - yMaxMove){
				target.y = centerPosition.y - yMaxMove;
			}

			transform.position = target;
		}
    }
}
